package com.tckdq.tcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tckdq.tcc.domain.Course;
import com.tckdq.tcc.domain.CourseMarket;
import com.tckdq.tcc.exception.GlobalException;
import com.tckdq.tcc.mapper.CourseMarketMapper;
import com.tckdq.tcc.service.ICourseChapterService;
import com.tckdq.tcc.service.ICourseMarketService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tckdq.tcc.service.ICourseService;
import com.tckdq.tcc.vo.CourseStateVO;
import org.aspectj.bridge.MessageWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-08-16
 */
@Service
public class CourseMarketServiceImpl extends ServiceImpl<CourseMarketMapper, CourseMarket> implements ICourseMarketService {

    @Autowired
    private ICourseService courseService;

    @Autowired
    private ICourseMarketService courseMarketService;
    @Override
    public CourseStateVO getCourseStateForUser(Long courseId) {
        if (StringUtils.isEmpty(courseId)){
            throw new GlobalException("课程ID不能为空",null);
        }
        Course course = courseService.selectById(courseId);
        if (StringUtils.isEmpty(course)){
            throw new GlobalException("课程为空",null);
        }

        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        if (StringUtils.isEmpty(courseMarket)){
            throw new GlobalException("课程为空",null);
        }
        //是否免费
        boolean isFree =(courseMarket.getCharge() != null && courseMarket.getCharge() == CourseMarket.CHARGE_FREE);
        //是否上线
        boolean isOnline =(course.getStatus() ==Course.STATUS_ONLINE);

        Long logId=3L;

        boolean isPurchsed =(null != selByCourseIdAndUserId(logId,courseId));

        CourseStateVO courseStateVO = new CourseStateVO();
        courseStateVO.setFree(isFree);
        courseStateVO.setOnline(isOnline);
        courseStateVO.setPurchased(isPurchsed);
        return courseStateVO;
    }

    private Course selByCourseIdAndUserId(Long logId, Long courseId) {
        EntityWrapper<Course> wrapper = new EntityWrapper<>();
        wrapper.eq("login_id",3L);
        wrapper.eq("id",courseId);
        Course course = courseService.selectOne(wrapper);
        return course;
    }
}
